/**
 * $Id: GetMTThread.java,v 1.39 2006/11/13 04:03:24 martin Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner.process;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.CommonMsgBean;
import com.haoxi.gateway.common.Queue;
import com.haoxi.gateway.common.SQLConst;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.messageconvertor.MessageConvertor;
import com.haoxi.gateway.runner.AbsIntoQueue;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.runner.smscommand.SubmitCmd;
import com.haoxi.gateway.runner.specialmobile.SpecialMobileMrg;
import com.haoxi.gateway.util.db.DBConnectUtil;
import com.haoxi.gateway.util.db.DealOracleDBUtil;

/**
 * 获得需要下发的MT，并进行业务处理
 * 
 * Revision History
 * 
 * 2006-5-29,star.Zhao,created it
 */
public class GetMTThread extends AbsIntoQueue {
    private static final Log log = LogFactory.getLog(GetMTThread.class);

    // private static final int Max_Chare_Num = 70;

    // special mobile deal info
    private static final String BLACK_MOBILE_INFO = "&Black mobile";
    private static final String SENSE_MOBILE_INFO = "&Sense mobile";
    private static final String BLACK_LONGNUM_INFO = "&Black longNumber";
    static int mtListLen = 0;
    private String currentGateway = (String) RunnerMgr.getInstance()
            .getGatewayInfo().getGatewayCode();
    // private static final int REASON_MT = 0; // 0-MO点播引起的第一条MT消息
    List errorInfoList = new ArrayList();
    private MessageConvertor convertor;
    private static final String MY_NAME = "GetMTThread";

    public GetMTThread(Queue toQueue, MessageConvertor convertor) {
        super(toQueue);
        this.convertor = convertor;
        setName(MY_NAME);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.haoxi.gateway.common.AbsIntoQueue#doJob()
     */
    public int doJob() {
        Map systemConf = RunnerMgr.getInstance().getSystemConf();
        String gateway_history = (String) systemConf
                .get(SYSConst.CONF_DB_HISTORY);
        String gateway_sms = (String) systemConf.get(SYSConst.CONF_DB_GATEWAY);
        int nRet = ACTION_ERROR;
        log
                .debug("--------Start get needed submit MT in GetMTThread.doJob()!-----------");
        // check dest queue
        Queue queue = getQueue();

        if (queue == null) {
            log.error("queue is null, please Check it !");
            return nRet;
        }

        // get mt list
       
        List list = getNeedSubmitMT(gateway_sms);
        log.debug("Select needed Submit MT count :[" + list.size() + "]");
        if (list != null && list.size() > 0) {
            int nLen = list.size();
            mtListLen = nLen;
            int[] ids = new int[nLen];
            int nIndexID = 0;

            Object obj = null;
            SubmitCmd mt = null;
            boolean bok = false;
            CommonMsgBean msgBean = null;
            for (int i = 0; i < nLen; i++) {
                obj = list.get(i);
                if (obj instanceof SubmitCmd) {
                    mt = (SubmitCmd) obj;
                    log.debug("start convert submitCmd");
                    // MessageConvertor
                    msgBean = convertor.convertCMDToCommonMsg(mt);
                   
                    log.debug("end convert submitCmd");
                    if (null != msgBean) {
                        // save MTcmd into CommonMsgBean's Reserve field for
                        // MT_RESPMap's Data

                        // into dest union mt queue
                        log.debug("插入MT对列");
                       
                        bok = queue.add(msgBean);
                       
                        if (!bok) {
                            nRet = ACTION_ERROR;
                            break;
                        } else {
                            ids[nIndexID] = mt.getId();
                            nIndexID++;
                            nRet = ACTION_NORMAL;
                        }
                        
                    }
                }
            }

            if (nIndexID > 0) {
                // DELETE DEALED MT'
                if (0 == errorInfoList.size()) {
                    // 屏蔽 by dean
                    DealOracleDBUtil.deleteDealed(ids, gateway_sms);
                    // end屏蔽
                }
                // delete error mt info
                else {
                    // save error history msg
                    ExceptionDateDeal.submitErrorDeal(DealOracleDBUtil
                            .createErrorSubmitList(errorInfoList,
                                    gateway_history));

                    int listLength = errorInfoList.size();
                    int errorIdx[] = new int[listLength];
                    for (int i = 0; i < listLength; i++) {
                        errorIdx[i] = Integer.parseInt(((String) errorInfoList
                                .get(i)).split("&")[0]);
                    }

                    // delete all get mt info (right + wrong)
                    int idsLength = ids.length;
                    int errorIdxLength = errorIdx.length;
                    int deleteIdx[] = new int[idsLength + errorIdxLength];
                    System.arraycopy(ids, 0, deleteIdx, 0, idsLength);// copy
                    // idx
                    // array
                    // to
                    // deleteIdx
                    // array
                    System.arraycopy(errorIdx, 0, deleteIdx, idsLength,
                            errorIdxLength);// copy errorIdx array to deleteIdx
                    // array
                    DealOracleDBUtil.deleteDealed(deleteIdx, gateway_history);
                    log.debug("the number of dealing result are: " + idsLength);
                    log.debug("the number of wrong result are: "
                            + errorIdxLength);
                    errorInfoList.clear();
                }
            }
        } else {
            nRet = ACTION_SLEEP;
        }
        // log.debug ( "Get needed submit MT in GetMTThread.doJob()
        // successfully!" );
        return nRet;
    }

    /**
     * get mt list
     * 
     * @return
     */
    private List getNeedSubmitMT(String dbName) {
        List list = new ArrayList();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Map sysCofn = RunnerMgr.getInstance().getSystemConf();
        int getMtSpeed = ((Integer) sysCofn.get(SYSConst.CONF_GETMT_SPEED))
                .intValue();
        try {
            conn = DBConnectUtil.open(dbName);
            log.debug("dbname:" +dbName);
            //ps = conn.prepareStatement(SQLConst.GET_NEED_SEND_MT);
//            ps.setString(1, currentGateway);
//            ps.setInt(2, getMtSpeed);
            ps = conn.prepareStatement(SQLConst.GET_NEED_SEND_MT_MySQL);
            rs = ps.executeQuery();
            log.debug("GET_NEED_SEND_MT_MySQL:" +SQLConst.GET_NEED_SEND_MT_MySQL);
            SubmitCmd mt = null;
            int mtId = 0;
           
            while (rs.next()) {
                mtId = rs.getInt("id");
                String mobile = rs.getString("destmobile");
                // if sense mobile , stop send and save the info into msg error!
                if (SpecialMobileMrg.isSenseMobile(mobile)) {
                    log.debug("Find sense mobile:[" + mobile
                            + "], It'll be forbidden to send.");
                    errorInfoList.add(mtId + SENSE_MOBILE_INFO);
                    continue;
                }

                // if black mobile , stop send and save the info into msg error!
                if (SpecialMobileMrg.isBlackMobile(mobile)) {
                    log.debug("Find black mobile:[" + mobile
                            + "], It'll be forbidden to send.");
                    errorInfoList.add(mtId + BLACK_MOBILE_INFO);
                    continue;
                }

                //号段过滤
                if (SpecialMobileMrg.isBlackMobile(mobile.substring(0, 8))) {
                    log.debug("Find black mobile:[" + mobile
                            + "], It'll be forbidden to send.");
                    errorInfoList.add(mtId + BLACK_MOBILE_INFO);
                    continue;
                }
                //号段过滤
                if (SpecialMobileMrg.isBlackMobile(mobile.substring(0, 7))) {
                    log.debug("Find black mobile:[" + mobile
                            + "], It'll be forbidden to send.");
                    errorInfoList.add(mtId + BLACK_MOBILE_INFO);
                    continue;
                }
                // if black mobile , stop send and save the info into msg error!
                String orgmobile = rs.getString("orgmobile");
                if (SpecialMobileMrg.isBlackLongNum(orgmobile)) {
                    log.debug("Find black longNumber:[" + orgmobile
                            + "], It'll be forbidden to send.");
                    errorInfoList.add(mtId + BLACK_LONGNUM_INFO);
                    continue;
                }

                mt = new SubmitCmd();
                mt.setId(mtId);
                mt.setStype(rs.getInt("stype"));
                mt.setGateWayCode(currentGateway);
                mt.setServiceId(rs.getString("Fee_Code"));
                mt.setPriority(rs.getInt("REPORTFLAG"));
                mt.setOrgMobile(rs.getString("orgmobile"));
                mt.setDestMobile(rs.getString("destmobile"));
                mt.setDestMobileType(rs.getInt("destmobiletype"));
                mt.setFeeMobile(rs.getString("feemobile"));
                mt.setFeeMobileType(rs.getInt("feemobiletype"));
                mt.setScheduleTime("");
                mt.setExpireTime("");
                // mt.setMtFlag(REASON_MT); // 10010 needed ,引起MT消息的原因
                mt.setMtFlag(rs.getInt("MTFLAG")); // 10010 needed ,引起MT消息的原因
                mt.setReg_del(rs.getInt("REG_DEL")); // need report
                mt.setMsgCoding(rs.getInt("msgfmt"));
                mt.setTpPId(rs.getInt("TPPID"));
                mt.setTpUdhi(rs.getInt("TPUDHID"));
                mt.setMsgContent(rs.getString("content"));
                mt.setFeeUserType(rs.getInt("FEE_USERTYPE"));
                String tmp = rs.getString("reserved");
                String link = "";
                String momtrelateID = "";
                if (null != tmp && !"".equals(tmp)) {
                    String temp[] = tmp.split(",");
                    switch (temp.length) {
                    case 0:
                        break;
                    case 1:
                        link = temp[0];
                        break;
                    case 2:
                        link = temp[0];
                        momtrelateID = temp[1];
                        break;
                    default:
                        break;
                    }
                }
                mt.setLinkID(link);
                mt.setMomtRelateID(momtrelateID);
                mt.setSid(rs.getString("tid"));
                mt.setCp(rs.getInt("cp"));
                mt.setFeeType(rs.getString("Fee_Type"));
                mt.setFeeCode(rs.getInt("FEEMONEY"));
                mt.setProvice(rs.getInt("PROVINCE"));
                mt.setCity(rs.getInt("CITYNUMBER"));
                mt.setCityName(rs.getString("CITYNAME"));
                // 电信网通需求，增加一个字段
                mt.setFeeRecript(rs.getInt("FEE_RECEIPT"));
                log.debug(mt);
                list.add(mt);
            }
            
            
        } catch (SQLException sqle) {
            log.error("SQLException in GetMTThread.getMTList()!", sqle);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log
                        .error(
                                "release db connection unsuccessfully in GetMTThread.getMTList()!",
                                sqle);
            }
        }

        return list;
    }
}
